package com.gpdaniels.controller.activity;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public final class permissions {
    private static final String TAG = new Object(){}.getClass().getEnclosingClass().getCanonicalName();

    public static final String[] get_all_required_permissions(Context context) {
        Log.d(TAG, new Object(){}.getClass().getEnclosingMethod().getName() + "()");
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS).requestedPermissions;
        } catch (PackageManager.NameNotFoundException exception) {
            Log.e(TAG, "Failed to get required permissions from package with error: ", exception);
        }
        return new String[]{};
    }

    public static final List<String> get_all_missing_permissions(Context context, String... permissions) {
        Log.d(TAG, new Object(){}.getClass().getEnclosingMethod().getName() + "()");
        List<String> missing_permissions = new ArrayList<>();
        for (String permission : permissions) {
            try {
                PermissionInfo permission_info = context.getPackageManager().getPermissionInfo(permission, PackageManager.GET_META_DATA);
                // Check permission is dangerous (and therefore needs to be requested).
                // API28+: if (permission_info.getProtection() != PermissionInfo.PROTECTION_DANGEROUS) {
                if (permission_info.protectionLevel != PermissionInfo.PROTECTION_DANGEROUS) {
                    continue;
                }
                // Check the permission is actually in the manifest as opposed to autogenerated.
                // TODO: ...
            } catch (PackageManager.NameNotFoundException exception) {
                Log.e(TAG, "Failed to find permission name with error: ", exception);
            }
            if (context.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                missing_permissions.add(permission);
            }
        }
        return missing_permissions;
    }
}
